const express = require('express')
const router = express.Router()

// 自定义库
const db = require('../config/database.js')
const code = require('../config/code.js')
const User = require('../model/user.js')
const redis = require('../config/redis.js')
const { makeRoomId } =  require('../utils/index.js')

router.get('/get', (req, res, next) => {
  (async () => {
    const { roomId } = req.query
    if (!roomId) {
      return res.json({code: code.paraErr, msg: '参数不足'})
    }
    const roomKey = 'room' + roomId
    if (await redis.exists(roomKey) === 0) {
      return res.json({code: code.paraErr, msg: '房间不存在'})
    }
    const roomInfo = await redis.hGetAll(roomKey)
    return res.json({
      code: code.ok,
      msg: '获取房间成功',
      data: {
        roomId: roomId,
        roomInfo: roomInfo
      }
    })
  })()
})
router.post('/add', (req, res, next) => {
  (async () => {
    let { roomTime } = req.body
    if (!roomTime || roomTime > 12 || roomTime < 1) {
      return res.json({code: code.paraErr, msg: '参数有误'})
    }
    roomTime = parseInt(roomTime)
    const [errFind, resFind] = await db.query(User.findAllById, [req.auth.id])
    if (errFind) {
      return res.json({code: code.dbErr, msg: '创建失败'})
    }
    if (resFind.length === 0) {
      return res.json({code: code.dbErr, msg: '创建失败'})
    }
    if (await redis.exists('owner' + resFind[0].id) !== 0) {
      const existRoomId = await redis.get('owner' + resFind[0].id)
      const existRoomInfo = await redis.hGetAll('room' + existRoomId)
      return res.json({
        code: code.ok,
        msg: '此用户已经创建过房间',
        data: {
          roomId: existRoomId,
          roomInfo: existRoomInfo
        }
      })
    }
    let roomId = makeRoomId()
    while (await redis.exists('room' + roomId) !== 0) {
      roomId = makeRoomId()
    }
    // 该成员是否已经上线
    const roomInfo = {
      owner: JSON.stringify(resFind[0]), // 房主
      roomId: roomId, // 房间id
      master: JSON.stringify(resFind[0]), // ppt控制者
      beginTime: Date.now(), // 开始时间
      roomTime: roomTime * 60 * 60, // 房间持续时长
      member: JSON.stringify({}),
      pptId: 0,
      ppt: JSON.stringify([]),
      pptPage: 0,
      chatMsg: [],
      volumePeer: JSON.stringify({}),
      drawCanv: JSON.stringify({
        version: '5.2.1',
        objects: [],
        background: '#FFFFFFFF'
      })
    }
    // 由于需要经常操作json中的一个字段，所以不打算用json转字符串存储，而是直接使用hash，将最常用的分离出来
    const roomKey = 'room' + roomId
    const ownerKey = 'owner' + resFind[0].id
    await redis.multi()
      .hSet(roomKey, 'owner', JSON.stringify(resFind[0]))
      .hSet(roomKey, 'roomId', roomId)
      .hSet(roomKey, 'master', JSON.stringify(resFind[0]))
      .hSet(roomKey, 'beginTime', Date.now())
      .hSet(roomKey, 'roomTime', roomTime * 60 * 60)
      .hSet(roomKey, 'member', JSON.stringify({}))
      .hSet(roomKey, 'pptId', 0)
      .hSet(roomKey, 'ppt', JSON.stringify([]))
      .hSet(roomKey, 'pptPage', 0)
      .hSet(roomKey, 'chatMsg', JSON.stringify([]))
      .hSet(roomKey, 'volumePeer', JSON.stringify({}))
      .hSet(roomKey, 'drawCanv', JSON.stringify({
        version: '5.2.1',
        objects: [],
        background: '#FFFFFFFF'
      }))
      .set(ownerKey, roomId)
      .expire(roomKey, roomTime * 60 * 60)
      .expire(ownerKey, roomTime * 60 * 60)
      .exec()
    return res.json({
      code: code.ok,
      msg: '创建房间成功',
      data: {
        roomId: roomId,
        roomInfo: roomInfo
      }
    })
  })()

})

module.exports = router